package com.duowan.cms.action.article;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.duowan.cms.action.AbstractController;
import com.duowan.cms.common.domain.Page;
import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.DateUtil;
import com.duowan.cms.common.util.IdManager;
import com.duowan.cms.common.util.LogUtil;
import com.duowan.cms.common.util.PathUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.dto.article.Article4TagListInfo;
import com.duowan.cms.dto.article.ArticleInfo;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.dto.tag.TagInfo;
import com.duowan.cms.dto.template.SimpleTemplateInfo;
import com.duowan.cms.dto.template.TemplateCategory;
import com.duowan.cms.dto.template.TemplateSearchCriteria;
import com.duowan.cms.dto.user.UserInfo;
import com.duowan.cms.dto.zone.ZoneUserInfo;
import com.duowan.cms.service.article.Article4TagListService;
import com.duowan.cms.service.article.ArticleService;
import com.duowan.cms.service.channel.ChannelService;
import com.duowan.cms.service.tag.TagService;
import com.duowan.cms.service.template.TemplateService;
import com.duowan.cms.service.zone.ZoneService;
import com.duowan.cms.util.RequestUtil;
/**
 * 
 * <p>作　　者：黄均杨
 * <p>完成日期：2012-12-14
 */
@Controller
public class ArticleController extends AbstractController {

	@Autowired
	private Article4TagListService article4TagListService;
	
	@Autowired
	private ArticleService articleService;

	@Autowired
	private ChannelService channelService;

	@Autowired
	private TagService tagService;

	@Autowired
	private TemplateService templateService;
	
	@Autowired
	private ZoneService zoneService;
	
	private static Logger logger = Logger.getLogger(ArticleController.class);
	
	@RequestMapping(value = "/article/toArticleUEditor", method = RequestMethod.GET)
	public String toArticleUEditor(HttpServletRequest request,
				HttpServletResponse response) throws IOException {
		return "/article/article_ueditor";
	}
	
	@RequestMapping(value = "/article/toArticleKindEditor", method = RequestMethod.GET)
	public String toArticleKindEditor(HttpServletRequest request,
				HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String userId = ((UserInfo) request.getSession().getAttribute("userInfo")).getUserId();
		String articleId = request.getParameter("articleId");
		 ChannelInfo channelInfo = (ChannelInfo)request.getSession().getAttribute("channelInfo");
		String tagJsonData = tagService.getTagsExcludeSpecialToJson(channelId);
		List<TagInfo> specialTagList = tagService.getSpecialTags(channelId);
		ArticleInfo articleInfo = new ArticleInfo();
		if (StringUtil.isEmpty(articleId)) {
			articleId = String.valueOf(IdManager.generateId());
			request.setAttribute("isAddArticle", true);
		} else {
			articleInfo = articleService.getByChannelIdAndArticleId(channelId, Long
						.parseLong(articleId));
			if (articleInfo != null) {
				String logs = articleInfo.getLogs();
				if (!StringUtil.isEmpty(logs)) {
					request.setAttribute("logArr", logs.split("<br>\n"));
				}
			}
			request.setAttribute("isAddArticle", false);
		}
		TemplateSearchCriteria templateSearchCriteria = new TemplateSearchCriteria();
		templateSearchCriteria.setChannelId(channelId);
		templateSearchCriteria.setTemplateCategory(TemplateCategory.FINAL_ARTICLE);
		Page<SimpleTemplateInfo> templateInfoPage = templateService.pageSearch4Show(templateSearchCriteria);
		List<ZoneUserInfo> zoneUserInfoList = zoneService.getZoneUserInfo(channelId);

		request.setAttribute("picUrlOnCms", PathUtil.getDomainOncms(channelId).replaceAll("http://", ""));// 获取图片在发布器服务器的URL前缀
		request.setAttribute("picUrlOnline", channelInfo.getPicDomain().replaceAll("http://", "") );// 获取图片在外网的URL前缀
		request.setAttribute("zoneUserInfoList", zoneUserInfoList);// 有爱账号
		request.setAttribute("templateInfoPage", templateInfoPage);// 最终文章页数据
		request.setAttribute("channelInfo", channelInfo);// 频道信息
		request.setAttribute("articleId", articleId);// 文章id
		request.setAttribute("tagJsonData", tagJsonData);// 普通标签的json格式的数据
		request.setAttribute("channelId", channelId);// 频道id
		request.setAttribute("userId", userId);// 用户id
		request.setAttribute("specialTagList", specialTagList);// 特殊标签列表
		request.setAttribute("articleInfo", articleInfo);// 若是修改文章，则可以得到文章信息
		request.setAttribute("nowTime", DateUtil.format(new Date(), DateUtil.defaultDateTimePatternStr));
		return "/article/article_kindeditor";
	}
	
	@RequestMapping(value = "/article/toArticleTagInclude", method = RequestMethod.GET)
	public String toArticleTagInclude(HttpServletRequest request,
				HttpServletResponse response) throws IOException {
		String width = request.getParameter("width");
		String currentTag = request.getParameter("currentTag");
		request.setAttribute("width", StringUtil.isEmpty(width) ?  "800" : width);// 页面宽度
		request.setAttribute("currentTag", StringUtil.isEmpty(currentTag) ?  "" : currentTag);// 在"文章列表"下的某个标签下发表空链接，把当前的标签默认显示出来
		request.setAttribute("isCurrentTagEmpty", StringUtil.isEmpty(currentTag) );// 
		return "/article/article_tag_include";
	}

	@RequestMapping(value = "/article/toEditEmptyLinkArticlePage", method = RequestMethod.GET)
	public String toEditEmptyLinkArticlePage(HttpServletRequest request,
				HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		String currentTag = request.getParameter("tag");
		String userId = ((UserInfo) request.getSession().getAttribute("userInfo")).getUserId();
		Article4TagListInfo article4TagListInfo = new Article4TagListInfo();
		if (!StringUtil.isEmpty(articleId)) {
			article4TagListInfo = article4TagListService.getByPrimaryKey(channelId, currentTag, Long.parseLong(articleId) );
		}else{
			articleId = String.valueOf(IdManager.generateId());
		}
		List<TagInfo> specialTagList = tagService.getSpecialTags(channelId);
		String tagJsonData = tagService.getTagsExcludeSpecialToJson(channelId);
		request.setAttribute("tagJsonData", tagJsonData);// 普通标签的json格式的数据
		request.setAttribute("specialTagList", specialTagList);// 特殊标签列表
		request.setAttribute("article4TagListInfo", article4TagListInfo);// 若是修改空链接，则可以得到空链接信息
		request.setAttribute("userId", userId);// 用户id
		request.setAttribute("articleId", articleId);// 文章id
		request.setAttribute("channelId", channelId);// 频道id
		request.setAttribute("currentTag", currentTag);// 频道id
		return "/article/article_emptylink_edit";
	}

	@RequestMapping(value = "/article/toEditArticlePage", method = RequestMethod.GET)
	public String toEditArticlePage(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String userId = ((UserInfo) request.getSession().getAttribute("userInfo")).getUserId();
		String articleId = request.getParameter("articleId");
		 ChannelInfo channelInfo = (ChannelInfo)request.getSession().getAttribute("channelInfo");
		String tagJsonData = tagService.getTagsExcludeSpecialToJson(channelId);
		List<TagInfo> specialTagList = tagService.getSpecialTags(channelId);
		ArticleInfo articleInfo = new ArticleInfo();
		if (StringUtil.isEmpty(articleId)) {
			articleId = String.valueOf(IdManager.generateId());
			request.setAttribute("isAddArticle", true);
		} else {
			articleInfo = articleService.getByChannelIdAndArticleId(channelId, Long
						.parseLong(articleId));
			if (articleInfo != null) {
				String logs = articleInfo.getLogs();
				if (!StringUtil.isEmpty(logs)) {
					request.setAttribute("logArr", logs.split("<br>\n"));
				}
			}
			request.setAttribute("isAddArticle", false);
		}

		TemplateSearchCriteria templateSearchCriteria = new TemplateSearchCriteria();
		templateSearchCriteria.setChannelId(channelId);
		templateSearchCriteria.setTemplateCategory(TemplateCategory.FINAL_ARTICLE);
		Page<SimpleTemplateInfo> templateInfoPage = templateService.pageSearch4Show(templateSearchCriteria);
		
		List<ZoneUserInfo> zoneUserInfoList = zoneService.getZoneUserInfo(channelId);

		request.setAttribute("picUrlOnCms", PathUtil.getDomainOncms(channelId).replaceAll("http://", ""));// 获取图片在发布器服务器的URL前缀
		request.setAttribute("picUrlOnline", channelInfo.getPicDomain().replaceAll("http://", "") );// 获取图片在外网的URL前缀
		
		request.setAttribute("zoneUserInfoList", zoneUserInfoList);// 有爱账号
		request.setAttribute("templateInfoPage", templateInfoPage);// 最终文章页数据
		request.setAttribute("channelInfo", channelInfo);// 频道信息
		request.setAttribute("articleId", articleId);// 文章id
		request.setAttribute("tagJsonData", tagJsonData);// 普通标签的json格式的数据
		request.setAttribute("channelId", channelId);// 频道id
		request.setAttribute("userId", userId);// 用户id
		request.setAttribute("specialTagList", specialTagList);// 特殊标签列表
		request.setAttribute("articleInfo", articleInfo);// 若是修改文章，则可以得到文章信息
		request.setAttribute("nowTime", DateUtil.format(new Date(), DateUtil.defaultDateTimePatternStr));
		return "/article/article_edit";
	}
	@RequestMapping(value = "/article/publishEmptyLink", method = RequestMethod.POST)
	public void publishEmptyLink(HttpServletRequest request, HttpServletResponse response,
				@ModelAttribute("article4TagListInfo") Article4TagListInfo article4TagListInfo) throws IOException,
				BaseCheckedException, ParseException {

		String tags = request.getParameter("tags");
	    ChannelInfo channelInfo = (ChannelInfo)request.getSession().getAttribute("channelInfo");
		String channelId = channelInfo.getId();
		article4TagListInfo.setChannelInfo(channelInfo);
		String publishTimeStr = request.getParameter("publishTimeStr");
		if (!StringUtil.isEmpty(publishTimeStr)) {
		    Date date = DateUtil.convertStr2Date( publishTimeStr );
		    article4TagListInfo.setPublishTime(date);
		    if(date.after(new Date())){
		        article4TagListInfo.setStatus(1);
		    }
        }
		
		// 1.预处理tags，去重复取得tagtree
		//String []noReaptTagArr = tagService.getTagTreeByPostTags(channelId, tags).split(",");
		List<Article4TagListInfo> article4TagListInfoList = new ArrayList<Article4TagListInfo>();
		for(String tag : getExistTags(channelId, tags)){
		    Article4TagListInfo newArticle4TagListInfo = new Article4TagListInfo(article4TagListInfo);
            newArticle4TagListInfo.setTag(tag);
            article4TagListInfoList.add(newArticle4TagListInfo);
		}
        if (!StringUtil.isEmpty(article4TagListInfo.getPictureUrl())) {
        	article4TagListInfo.setTag("图片");
        	article4TagListInfoList.add(article4TagListInfo);
        }

		articleService.publishEmptyLink(channelId , article4TagListInfoList);
	}
	
	private List<String> getExistTags(String channelId, String tags){
	    List<String> tagList = new ArrayList<String>();
	    if(StringUtil.isEmpty(tags))
	        return tagList;
	    
	    String[] tagArray = tags.split(",|;");
	    for(String tag : tagArray){
	        if(tagService.isExist(channelId, tag))
	            tagList.add(tag);
	    }
	    return tagList;
	}

	@RequestMapping(value = "/article/publish", method = RequestMethod.POST)
	public String publish(HttpServletRequest request, HttpServletResponse response,
				@ModelAttribute("articleInfo") ArticleInfo articleInfo) throws IOException,
				BaseCheckedException, ParseException {
	    ChannelInfo channelInfo = (ChannelInfo)request.getSession().getAttribute("channelInfo");
		String channelId =channelInfo.getId();
		String userId = request.getParameter("userId");
		String articleId = request.getParameter("id");
		String isAddArticle = request.getParameter("isAddArticle");
		
		/* 校验数据合法性 */
		if (articleService.checkTitleIsExisted(channelId,articleId, request.getParameter("title"))) {
			logger.error("编辑文章失败，原因：标题已存在");
			throw new BaseCheckedException("", "编辑文章失败，原因：标题已存在");
		}
		if ("true".equals(isAddArticle)) {// 新增
			articleInfo.setLogs(RequestUtil.getRequestLog(request));
		} else {// 修改
			articleInfo.setLogs(LogUtil.getLogBeforeTen(RequestUtil.getRequestLog(request)
						+ articleInfo.getLogs()));
		}
		String prePublishTime = request.getParameter("prePublishTimeStr");
		if (!StringUtil.isEmpty(prePublishTime)) {
			articleInfo.setPrePublishTime(DateUtil.convertStr2Date( prePublishTime ));
		}
		Long threadId = 0L;
		if(articleInfo.isNeedComment()){
		    threadId = articleInfo.getId();
		}
		articleInfo.setThreadId(threadId);
		articleInfo.setChannelInfo(channelService.getById(channelId));
		articleInfo.setProxyIp(RequestUtil.getProxyIp(request));
		articleInfo.setUserIp(RequestUtil.getUserIp(request));
		
		articleService.publish(articleInfo);
		
		if ("true".equals(isAddArticle)) {// 新增
			//发布后，到新的发布文章页面
			return "redirect:/article/toEditArticlePage.do?channelId=" + channelId + "&userId="+ URLEncoder.encode(userId, "utf8") ;
		}
		//发布后到编辑文章页面
		return "redirect:/article/toEditArticlePage.do?articleId=" + articleId + "&channelId=" + channelId;

	}

	/**
	 *	删除文章 
	 */
	@RequestMapping(value = "/article/deleteArticle", method = RequestMethod.GET)
	public String deleteArticle(HttpServletRequest request, HttpServletResponse response)
				throws IOException, NumberFormatException, BaseCheckedException {
		UserInfo userInfo = 	(UserInfo) request.getSession().getAttribute("userInfo");
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		articleService.delete(userInfo , channelId, Long.parseLong(articleId));
		return "redirect:/article/articleRoll.do?channelId=" + channelId;
	}
	
	/**
	 * 隐藏文章
	 */
	@RequestMapping(value = "/article/hideArticle", method = RequestMethod.GET)
	public void hideArticle(HttpServletRequest request, HttpServletResponse response)
				throws IOException, NumberFormatException, ParseException, BaseCheckedException {
		UserInfo userInfo = 	(UserInfo) request.getSession().getAttribute("userInfo");
		String channelId = request.getParameter("channelId");
		String articleId = request.getParameter("articleId");
		articleService.hide(userInfo ,channelId, Long.parseLong(articleId));
	}
	

	
	@RequestMapping(value = "/article/checkTitle", method = RequestMethod.GET)
	public void checkTitle(HttpServletRequest request, HttpServletResponse response)
				throws IOException {
		String channelId = request.getParameter("channelId");
		String title = request.getParameter("title");
		String articleId = request.getParameter("articleId");
		if (articleService.checkTitleIsExisted(channelId, articleId ,title)) {
			response.getWriter().write("exist");
		}
	}
	
	@RequestMapping(value = "/article/updatePublishTime", method = RequestMethod.POST)
    public String updatePublishTime(HttpServletRequest request, HttpServletResponse response)
                throws IOException, NumberFormatException, ParseException, BaseCheckedException {
        String channelId = request.getParameter("channelId");
        String articleId = request.getParameter("articleId");
        String newPublishTimeStr = request.getParameter("newPublishTimeStr");
        articleService.updatePublishTime(channelId, Long.parseLong(articleId), DateUtil.convertStr2Date(newPublishTimeStr));
        
        return "redirect:/article/toEditArticlePage.do?articleId=" + articleId + "&channelId=" + channelId;
    }
    
}
